﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Oxite;
using Oxite.Infrastructure;
using System.Web.Routing;
using Oxite.Extensions;

namespace Oxite.Skinning
{
    public static class SkinningTool
    {
        public static void SetupSkinViewEngines(ISkinResolverRegistry skinResolvers, OxiteContext context,RequestContext requestContext, ViewDataDictionary viewData, ViewResultBase result)
        {
            HttpRequestBase request = requestContext.HttpContext.Request;
            string appPath = request.ApplicationPath != "/" ? request.ApplicationPath : "";
            string queryStringSkinName = request.QueryString["skin"];
            string cookieSkinName = request.Cookies.GetSkinName();
            string skin = "";

            if (!string.IsNullOrEmpty(queryStringSkinName))
                skin = queryStringSkinName;
            else if (!string.IsNullOrEmpty(cookieSkinName))
                skin = cookieSkinName;

            if (skin == "" && request.Url.PathAndQuery.StartsWith(appPath + "/Admin", StringComparison.OrdinalIgnoreCase))
                skin = context.Site.AdminSkin;

            if (skin == "")
                skin = !string.IsNullOrEmpty(viewData["Skin"] as string)
                    ? viewData["Skin"] as string
                    : context.Site.Skin;


            IEnumerable<IOxiteViewEngine> viewEngines = skinResolvers.GenerateViewEngines(new SkinResolverContext(requestContext, skin), skin);
            ViewEngineCollection vec = new ViewEngineCollection(viewEngines.Cast<IViewEngine>().ToList()); // add by zhangxj @2009-11-23
            if (result != null)
            {
                result.ViewEngineCollection = vec; // new ViewEngineCollection(viewEngines.Cast<IViewEngine>().ToList()); //modi by zhangxj@2009-11-23

                result.ViewData["OxiteViewEngines"] = vec; //viewEngines; //TODO:modi by zhangxj@2009-11-23
            }

            viewData["OxiteViewEngines"] = vec;// viewEngines; //TODO:modi by zhangxj@2009-11-23
        }
    }
}
